package filters

import (
	"bytes"
	"encoding/json"
	"io"
	"strings"

	"boomlive.com/boomlive-common/constants"
	"boomlive.com/boomlive-common/utils"
	"github.com/beego/beego/v2/core/logs"
	beecontext "github.com/beego/beego/v2/server/web/context"
	"github.com/google/uuid"
)

func FilterRequestLog(ctx *beecontext.Context) {
	requestId := generateRequestId()
	ctx.Input.SetData("requestId", requestId)

	proxyIp := ctx.Request.RemoteAddr
	clientIp := ""

	// 获取原始请求的 IP
	forwardedFor := ctx.Input.Header("X-Forwarded-For")
	if forwardedFor != "" {
		clientIp = strings.Split(forwardedFor, ",")[0]
	} else {
		clientIp = ctx.Input.Header("X-Real-IP")
	}

	logMsg := "requestId=%s, proxyIp=%s, clientIp=%s, requestUri=%s, requestMethod=%s, requestContentType=%s, requestBody=%v"
	logData := []interface{}{requestId, proxyIp, clientIp, ctx.Input.URI(), ctx.Input.Method(), ctx.Input.Header("Content-Type")}

	// ✅ 手动读取并缓存 RequestBody
	bodyBytes := ctx.Input.RequestBody
	if len(bodyBytes) == 0 {
		bodyBytes, _ = io.ReadAll(ctx.Request.Body)
		ctx.Input.RequestBody = bodyBytes
		// 还原 Request.Body 以便后续再次读取
		ctx.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	}

	var requestBody interface{}
	if err := json.Unmarshal(bodyBytes, &requestBody); err == nil {
		logData = append(logData, string(bodyBytes))
	} else {
		logData = append(logData, "(NotJson)")
	}

	logs.Info(logMsg, logData...)
}

func generateRequestId() string {
	return utils.Md5(uuid.New().String())
}

func requestValidateFail(ctx *beecontext.Context) {
	res := utils.GenerateResultBody(constants.ERR_PARAM, nil, utils.GetLanguageCode(ctx))
	_ = ctx.Output.JSON(res, false, false)
}
